package com.ruoyi.server.MQTT.config;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.integration.annotation.IntegrationComponentScan;

@Configuration
@DependsOn("mqttBroker")
@IntegrationComponentScan
public class MqttClientConfig {
    
    private static final String BROKER_URL = "tcp://localhost:9009";
    private static final String CLIENT_ID = "spring-boot-mqtt-client";
    
    @Bean
    public MqttConnectOptions mqttConnectOptions() {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setAutomaticReconnect(true);    // 自动重连
        options.setCleanSession(false);         // 保留会话状态
        options.setConnectionTimeout(30);      // 超时时间
        options.setKeepAliveInterval(60);       // 心跳间隔
        return options;
    }
    
    @Bean
    public MqttClient mqttClient(MqttConnectOptions options) throws MqttException {
        MqttClient client = new MqttClient(BROKER_URL, CLIENT_ID, new MemoryPersistence());
        client.connect(options);
        return client;
    }
}

